package com.zyh.flink.day02.transform;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class ReduceTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> dataStream = environment.fromElements("hello world","hello baizhi","hello flink");
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = dataStream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] words = s.split("\\s+");
                for (String word : words) {
                    collector.collect(word);
                }
            }
        }).map(t -> Tuple2.of(t, 1)).returns(Types.TUPLE(Types.STRING,Types.INT))
                .keyBy(t -> t.f0);
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
            /*
            * 第一次计算 value1是第一个元素,value2是第二个元素
            * 第二次计算 value1是上一次计算的结果,value2是下一个元素
            * */
            @Override
            public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
                System.out.println("执行reduce()");
                return Tuple2.of(value1.f0, value1.f1 + value2.f1);
            }
        });
        result.print();
        environment.execute("ReduceJob");
    }
}
